//
//  ViewController.m
//  pricvyPhoto
//
//  Created by XingShuai on 2020/9/25.
//  Copyright © 2020 dashuai. All rights reserved.
//

#import "ViewController.h"

#import <PhotosUI/PhotosUI.h>

@interface ViewController () <PHPickerViewControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIImageView *img;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(100, 100, 100, 40);
    button.backgroundColor = [UIColor orangeColor];
    [button setTitle:@"选择相册照片" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    self.img = [[UIImageView alloc]initWithFrame:CGRectMake(100, 200, 200, 200)];
    self.img.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [self.view addSubview:self.img];
}

#pragma mark -- 点击选择照片
-(void)clickButton {
    
    // 以下 API 仅为 iOS14 only
    if (@available(iOS 14, *)) {
        PHPickerConfiguration *configuration = [[PHPickerConfiguration alloc] init];
        configuration.filter = [PHPickerFilter imagesFilter]; // 可配置查询用户相册中文件的类型，支持三种
        configuration.selectionLimit = 1; // 默认为1，为0时表示可多选。

        PHPickerViewController *picker = [[PHPickerViewController alloc] initWithConfiguration:configuration];
        picker.delegate = self;
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:picker animated:YES completion:nil];

    } else {
        // IOS other versions
        
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
        picker.allowsEditing = YES;
        picker.delegate = self;
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:picker animated:YES completion:nil];
    }
    
}

#pragma mark -- ios14相册图片选择代理
-(void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results  API_AVAILABLE(ios(14)){
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (!results || !results.count) {
        return;
    }
    NSItemProvider *itemProvider = results.firstObject.itemProvider;
    if ([itemProvider canLoadObjectOfClass:UIImage.class]) {
        __weak typeof(self) weakSelf = self;
        [itemProvider loadObjectOfClass:UIImage.class completionHandler:^(__kindof id<NSItemProviderReading>  _Nullable object, NSError * _Nullable error) {
            if ([object isKindOfClass:UIImage.class]) {
                __strong typeof(self) strongSelf = weakSelf;
                dispatch_async(dispatch_get_main_queue(), ^{
                    strongSelf.img.image = (UIImage *)object;
                });
                
                // 获取图片大小（MB）
                NSData *imgData = UIImageJPEGRepresentation(object, 1);

                // 图片大小
                NSLog(@"mb = %@",[self bytesToAvaiUnit:[imgData length]]);
                
                // 保存图片才会弹出图片权限
                //[self saveImageToPhotos:object];
            }
        }];
    }
}

#pragma mark -- ios14以下上传图片的协议与代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self dismissViewControllerAnimated:YES completion:nil];
    
    self.img.image = image;
    
    // 获取图片大小（MB）
    NSData *imgData = UIImageJPEGRepresentation(image, 1);

    // 图片大小
    NSLog(@"MB = %@",[self bytesToAvaiUnit:[imgData length]]);
}

// 获取图片大小（MB）
-(NSString *)bytesToAvaiUnit:(int64_t)bytes {
    /**
    if (bytes < 1024) {      // B
        return [NSString stringWithFormat:@"%lldB", bytes];
    } else if (bytes >= 1024 && bytes < 1024 * 1024) {                  // KB
        return [NSString stringWithFormat:@"%.1fKB", (double)bytes / 1024];
    } else if (bytes >= 1024 * 1024 && bytes < 1024 * 1024 * 1024) {    // MB
        return [NSString stringWithFormat:@"%.2fMB", (double)bytes / (1024 * 1024)];
    } else {                // GB
        return [NSString stringWithFormat:@"%.3fGB", (double)bytes / (1024 * 1024 * 1024)];
    }
    */
    return [NSString stringWithFormat:@"%.2lfMB", (double)bytes / (1024 * 1024)];
}



// 保存图片
- (void)saveImageToPhotos:(UIImage*)savedImage {
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    if(error != NULL) {
        NSLog(@"保存图片失败");
    } else {
        NSLog(@"保存图片成功");;
    }
}


@end
